package com.qianbei.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseApplication;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.service.DeleteFileService;
import com.qianbei.service.PushMsgService;
import com.qianbei.user.ChangePwdActivity;
import com.qianbei.user.FindPasswdActivity;
import com.qianbei.user.model.UserMode;
import com.qianbei.view.binding.AddBingActivity;
import com.qianbei.view.binding.UnBingActivity;
import com.qianbei.view.bluetooth.BluetoothService;
import com.qianbei.view.transport.RecordweightActivity;
import com.qianbei.view.transport.TransportfActivity;
import com.qianbei.view.util.TextUtil;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by gaoml on 2018/1/17.
 */

public class HomeActivity extends BaseActivity {

    @Bind(R.id.view_1)
    LinearLayout view1;
    @Bind(R.id.view_0)
    LinearLayout view0;
    @Bind(R.id.view_2)
    LinearLayout view2;
    @Bind(R.id.view_3)
    LinearLayout view3;

    @Bind(R.id.get_car2)
    TextView zhouzx;
    @Bind(R.id.get_car3)
    TextView tvCar3;
    @Bind(R.id.get_car5)
    TextView tvCar5;
    int jobBusinessType = -1;
    private HomeActivity context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CrashReport.setUserId(SetData.getUserPhone());
        setContentView(R.layout.gufei_home_activity);
        context = this;
        ButterKnife.bind(this);

        //第一次进来,
        if (TextUtils.isEmpty(SetData.getUserID())) {
            startActivity(LoginActivity.class);
            finish();
            return;
        }
        //刷新登录,看密码是否过期
        refeshLogin();
        refeshMoreThan90();


        setTitle("首页");
        mTitle.setLfetText("退出");
        mTitle.setrightTitle("设置功率");

        deleteFileAWeekAgo();
        // 轮询服务 处理没网情况下数据缓存在网络恢复时自动提交
        startService(new Intent(getApplicationContext(), PushMsgService.class));

        if (SetData.getUserRole().equals("driver")) {
            view1.setVisibility(View.VISIBLE);
            view0.setVisibility(View.VISIBLE);
            view2.setVisibility(View.GONE);
            view3.setVisibility(View.GONE);
        } else if (SetData.getUserRole().equals("boxManager")) {
            view1.setVisibility(View.GONE);
            view0.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
            view3.setVisibility(View.GONE);

        } else if (SetData.getUserRole().equals("station")) {
            view1.setVisibility(View.GONE);
            view0.setVisibility(View.GONE);
            view2.setVisibility(View.GONE);
            view3.setVisibility(View.VISIBLE);
        } else if (SetData.getUserRole().equals("lighterManager")) {
            view1.setVisibility(View.GONE);
            view0.setVisibility(View.VISIBLE);
            view2.setVisibility(View.GONE);
            view3.setVisibility(View.GONE);
            tvCar3.setText("驳运");
            tvCar5.setText("新增驳运");
        }

        checkJobTypeAndHideFun();

    }

    private void refeshMoreThan90() {
        if (SetData.getMoreThan90()) {
            AlertDialog alertDialog2 = new AlertDialog.Builder(context)
                    .setTitle("安全提示")
                    .setMessage("当前密码已经超过90天未修改,为保证信息安全,请立即修改!")
                    .setPositiveButton("去修改", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface d, int i) {
                            d.dismiss();
                            startActivity(new Intent(context, ChangePwdActivity.class));

                        }
                    })
                    .create();
            alertDialog2.show();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (TextUtils.isEmpty(SetData.getUserID())) {
            logout();
        }

        //未登录,重新进来,走这里
        if (TextUtils.isEmpty(SetData.getToken())) {
            //先退出
            String url = ServerControl.URL + ServerControl.url_p_logout;
            final ServerControl sc = new ServerControl(Request.Method.POST,
                    url);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    //再登录
                    refeshLogin();
                }
            };
            sc.startVolley();
        }
    }

    ///登出接口
    private void logout() {
        String url = ServerControl.URL + ServerControl.url_p_logout;
        final ServerControl sc = new ServerControl(Request.Method.POST,
                url);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                SetData.setUserID("");
                SetData.setPass("");
                finish();
                startActivity(LoginActivity.class);
            }
        };
        sc.startVolley();
    }

    private void refeshLogin() {
        String url = ServerControl.URL + ServerControl.url_p_login;
        org.json.JSONObject obj = new org.json.JSONObject();
        try {
            obj.put("username", SetData.getUSER());
            obj.put("password", SetData.getPSW());
        } catch (JSONException e) {
        }
        ServerControl sc = new ServerControl(Request.Method.POST,
                url, obj);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                Log.d("测试登录", "自动登录" + sr.toString());
                if (sr.isContinue) {
                    initData();
                    final org.json.JSONObject body = sr.bodyData.optJSONObject("data");
                    SetData.setUserID(body.optString("userId"));
                    SetData.setToken(body.optString("token"));
                    boolean moreThan90 = body.optBoolean("setMoreThan90");
                    if (moreThan90) {
                        //需要去修改密码
                        AlertDialog alertDialog2 = new AlertDialog.Builder(context)
                                .setTitle("安全提示")
                                .setMessage("当前密码已经超过90天未修改,为保证信息安全,请立即修改!")
                                .setPositiveButton("去修改", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                    @Override
                                    public void onClick(DialogInterface d, int i) {
                                        d.dismiss();
                                        startActivity(new Intent(context, ChangePwdActivity.class));

                                    }
                                })
                                .setNegativeButton("下次再说", new DialogInterface.OnClickListener() {//添加普通按钮
                                    @Override
                                    public void onClick(DialogInterface d, int i) {
                                        d.dismiss();
                                    }
                                })
                                .create();
                        alertDialog2.show();
                    }
                } else {
                    //登录失败的话,重新登录
                    finish();
                    startActivity(LoginActivity.class);
                }
            }
        };
        sc.startVolley();
    }

    //登录成功后,获取数据
    private void initData() {
        RequeastBean1 bean = new RequeastBean1("select",
                "com.cygps.dubbo.commons.data.ICommonDataService",
                new Basebean(), "WT_Bluetooth");

        ServerControl sc = new ServerControl(bean);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                Log.d("车辆", "返回: " + sr.toString());
                try {
                    org.json.JSONObject mObj = new org.json.JSONObject(sr.bodyData.toString());
                    org.json.JSONArray array = mObj.getJSONArray("array");
                    for (int i = 0; i < array.length(); i++) {
                        BaseApplication.mCarMap.put(array.getJSONObject(i).getString("bluetoothId"),
                                array.getJSONObject(i).getString("vehicleNo"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        sc.OKpost1();
    }

    //每次登陆删除一周之前的照片
    private void deleteFileAWeekAgo() {
        startService(new Intent(this, DeleteFileService.class));
    }

    /**
     * 当 businessType 是3  固废时 不显示周转箱装卸功能 固废没有周转箱
     */
    private void checkJobTypeAndHideFun() {
        if (!TextUtils.isEmpty(SetData.getJobid())) {
            String jsonString = SetData.getJobs();
            JSONArray jobsAry = JSON.parseArray(jsonString);
            String jobId = SetData.getJobid();
            if (jobsAry == null) {
                return;
            }
            for (int i = 0; i < jobsAry.size(); i++) {
                JSONObject oneJob = jobsAry.getJSONObject(i);
                String dataJobId = oneJob.getString("_id");
                if (dataJobId.equals(jobId)) {
                    int businessType = oneJob.getInteger("businessType");
                    jobBusinessType = businessType;
                    Log.d("businessType", businessType + " ");
                    if (businessType == 3) {
                        Drawable nav_up = getResources().getDrawable(R.drawable.gufei2_zhaungzai_disable);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                        zhouzx.setCompoundDrawables(null, nav_up, null, null);
                    } else {
                        Drawable nav_up = getResources().getDrawable(R.drawable.gufei2_zhaungzai);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                        zhouzx.setCompoundDrawables(null, nav_up, null, null);
                    }
                    break;
                }
            }
        }
    }

    @Override
    public void fClick(int id) {
        switch (id) {
            case R.id.title_left:
                logout();//注销按钮
                break;
            case R.id.tv_right:
                startActivity(SetActivity.class);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.get_car, R.id.get_car2, R.id.get_car3, R.id.get_car4, R.id.get_car5,
            R.id.get_car6, R.id.get_car7})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.get_car:
                startActivity(GetCarActivity.class);
                break;
            case R.id.get_car2:
                if (jobBusinessType == 3) {
                    new MsgAlert().show("固废业务不需要装卸周转箱");
                } else {
                    startActivity(BoxUPActivity.class);
                }
                break;
            case R.id.get_car3:
                if (SetData.getUserRole().equals("lighterManager")) {
                    startActivity(LighterActivity.class);
                } else {
                    startActivity(TransportfActivity.class);
                }
                break;
            case R.id.get_car4:
                startActivity(UnloadActivity.class);
                break;
            case R.id.get_car5:
                if (SetData.getUserRole().equals("lighterManager")) {
                    startActivity(AddLighterActivity.class);
                } else {
                    startActivity(CourseActivity.class);
                }
                break;
            case R.id.get_car6:
                startActivity(AddBingActivity.class);
                break;
            case R.id.get_car7:
                startActivity(UnBingActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        logout();
        BluetoothService.getInstance().stop();
    }

    //查看日志
    public void onSeeLogClick(View view) {
        SharedPreferences sp = getSharedPreferences(TextUtil.shhc_gfwl_sp, Context.MODE_PRIVATE);
        String msgSp = sp.getString(TextUtil.commitKey, "");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(msgSp);
        builder.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface d, int i) {
                d.dismiss();
            }
        });


        builder.show();
    }


    private boolean isExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //2s内按2次返回键退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {//第2次返回键
                finish();
            } else {//第一次返回键
                isExit = true;
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
                Toast.makeText(context, "再按一次退出!", Toast.LENGTH_LONG).show();
                return true;// true:表示自己已经处理按键事件, false:表示系统处理
            }
        }
        return super.onKeyDown(keyCode, event);

    }
}
